package com.demo.gulimall.search.controller;

import com.alibaba.fastjson.JSON;
import com.demo.gulimall.common.utils.R;
import com.demo.gulimall.search.config.MallElasticSearchConfig;
import com.demo.gulimall.search.entity.User;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author Chen Yuan
 * @create 2023-05-25  16:17
 */
@RestController
public class TestController {
	@Autowired
	private RestHighLevelClient restHighLevelClient;

	@GetMapping("/test/es")
	public void testES(){
		System.out.println(restHighLevelClient);
	}

	@GetMapping("/es/save")
	public void testESSave() throws IOException {
		// 1. 创建请求
		// 构造函数传入索引名称
		IndexRequest users = new IndexRequest("users");
		users.id("1"); // 设置 ID
		// 方式一: 通过 KV 键值对传入 Source
		//users.source("userName", "ZhangSan", "age", 20, "gender", "男");

		// 方式二: 直接将对象转成 JSON 格式传入
		User user = new User("ZhangSan", "男", 20);
		users.source(JSON.toJSONString(user), XContentType.JSON);

		// 2. 执行请求
		IndexResponse index = restHighLevelClient.index(users, MallElasticSearchConfig.COMMON_OPTIONS);

		// 3. 执行结果
		System.out.println(index);
	}

	public void testSearchData() throws IOException {
		// 1. 创建索引请求
		SearchRequest searchRequest = new SearchRequest();
		// 指定索引
		searchRequest.indices("bank");
		// 指定索引条件
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		// 构造检索条件
		searchSourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));

		searchRequest.source(searchSourceBuilder);


		// 执行请求
		SearchResponse searchResponse = restHighLevelClient.search(searchRequest, MallElasticSearchConfig.COMMON_OPTIONS);

		// 分析结果
		System.out.println(JSON.toJSONString(searchResponse));
	}
}
